/**
 * 
 */
package cn.mibcxb.java.dolphin.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import cn.mibcxb.java.dolphin.common.Commons;
import cn.mibcxb.java.dolphin.common.DolphinData;
import cn.mibcxb.java.dolphin.exception.DolphinException;

/**
 * @author CXB
 * 
 */
public class Receiver {
	private static Receiver mReceiver = null;
	private static boolean mFlag = true;
	private DolphinConsole console = null;

	private Receiver(DolphinConsole console) {
		this.console = console;
	}

	private DatagramSocket socket = null;

	private Thread mRunner = new Thread() {

		@Override
		public void run() {
			DatagramPacket packet = null;
			byte[] buffer = null;
			try {
				socket = new DatagramSocket(Commons.MSG_PORT);
				while (mFlag) {
					buffer = new byte[Commons.BUFFER_LENGTH];
					packet = new DatagramPacket(buffer, buffer.length);
					socket.receive(packet);
					DolphinData data = DolphinData.rebuildFromByte(packet
							.getData());
					if (null != data) {
						data.setFromAddr(packet.getAddress());
						consumeMsg(data);
					}
					console.printMessage("Receiver : done");
				}
			} catch (SocketException e) {
				if (mFlag) {
					e.printStackTrace();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (DolphinException e) {
				e.printStackTrace();
			} finally {
				if (null != socket) {
					socket.close();
				}
			}
		}
	};

	public static Receiver getInstance(DolphinConsole console) {
		if (null == mReceiver) {
			mReceiver = new Receiver(console);
		}
		return mReceiver;
	}

	public void start() {
		mRunner.start();
	}

	public void stop() {
		mFlag = false;
		if (null != mRunner) {
			if (null != socket) {
				socket.close();
				socket = null;
			}
			mRunner.interrupt();
		}
	}

	public boolean isAlive() {
		return null != mRunner && mRunner.isAlive();
	}

	// private void consumeMsg(InetAddress addr, String msg) {
	// if (StringUtils.isNotBlank(msg)) {
	// String[] temp = StringUtils.split(msg, Commons.SEPARATOR);
	// if (temp.length > 1) {
	// if (StringUtils.startsWithIgnoreCase(temp[0], "CONNECT")) {
	// Dolphin dolphin = new Dolphin(console, 0, temp[1], addr);
	// console.addDolphin(dolphin);
	// } else if (StringUtils.startsWithIgnoreCase(temp[0], "CHAT")) {
	// Dolphin dolphin = console.getFriend(addr);
	// if (null != dolphin) {
	// console.printMessage("From " + dolphin.getName()
	// + ":\"" + temp[1] + "\"");
	// } else {
	// console.printMessage("From " + addr + ":\"" + temp[1]
	// + "\"");
	// }
	// }
	// }
	// }
	// }

	private void consumeMsg(DolphinData data) {
		console.dispatchData(data);
		String address = data.getFromAddr().toString();
		String msg = data.getMsg();
		console.printMessage("Receiver: addr = " + address + ":" + msg);
	}
}
